package com.uu.safeguard.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;


/**
 * Jedis工具类
 */
@Component
public final class JedisUtil {
    private static JedisPool jedisPool;

    @Autowired
    private Environment env;

    @PostConstruct
    public void config() {
        //获取数据，设置到JedisPoolConfig中
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(Integer.parseInt(env.getProperty("spring.redis.jedis.pool.max-total")));
        config.setMaxIdle(Integer.parseInt(env.getProperty("spring.redis.jedis.pool.max-idle")));
        //初始化JedisPool
        jedisPool = new JedisPool(config, env.getProperty("spring.redis.host"), Integer.parseInt(env.getProperty("spring.redis.port")),Integer.parseInt(env.getProperty("spring.redis.timeout")),env.getProperty("spring.redis.password"));
    }


    /**
     * 获取连接方法
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    /**
     * 关闭Jedis
     */
    public static void close(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
}
